package demo1.helloworld;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer1 {


    public static void main(String[] args) throws IOException, InterruptedException, TimeoutException {
        // 打开连接并创建频道
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 声明队列，主要为了防止消息接收者先运行此程序，队列还不存在时创建队列。
        String queueName1 = "queue1";
        channel.queueDeclare(queueName1, true, false, false, null);

        // 定义topic类型的exchange并绑定队列
        String exChangeName = "change1";
        channel.exchangeDeclare(exChangeName, "topic");
        channel.queueBind(queueName1, exChangeName, "key.123.#");  // routingkey唯一
        System.out.println("Waiting for messages. To exit press Ctrl+C");

        // 创建队列消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName1, true, consumer);
        while (true) {
            // nextDelivery是一个阻塞方法（内部实现其实是阻塞队列的take方法）
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            System.out.println("[x] Received: " + message);
        }
    }
}
